package com.example.joysinfo.lkc;

import android.*;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.joysinfo.lkc.bean.Codebean;
import com.example.joysinfo.lkc.bean.Loginbean;
import com.example.joysinfo.lkc.http.LikoushanApi;
import com.example.joysinfo.lkc.http.ResponseInterface;
import com.example.joysinfo.lkc.util.CheckNetwork;
import com.example.joysinfo.lkc.util.LocalStorageUtil;
import com.example.joysinfo.lkc.util.Sharedpreference;
import com.example.joysinfo.lkc.util.ToastUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.io.File;

import hei.permission.PermissionActivity;

/**
 * Created by joysinfo on 2017/6/8.
 */
public class LoginActivity extends PermissionActivity {

    private ImageView codeimg;
    private EditText editText_username;
    private EditText editText_passwd;
    private EditText editText_code;
    private String name="";
    private String passwd="";
    private String code="";
    private LocalStorageUtil mLocalStorageUtil;
    private DisplayImageOptions headDisplayOption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        checkPermission(new CheckPermListener() {
                            @Override
                            public void superPermission() {
                                TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                                String szImei = TelephonyMgr.getDeviceId();
                                LikoushanApi.imei = szImei;
                                Log.d("deviceid  ", szImei);
                                getCode();

                            }
                        }, "给我",
                Manifest.permission.READ_PHONE_STATE,Manifest.permission.ACCESS_COARSE_LOCATION);

//        ,Manifest.permission.LOCATION_HARDWARE,
//                Manifest.permission.ACCESS_FINE_LOCATION

        codeimg= (ImageView) findViewById(R.id.codeimg);
        editText_username= (EditText) findViewById(R.id.editText_username);
        editText_passwd= (EditText) findViewById(R.id.editText_passwd);
        editText_code= (EditText) findViewById(R.id.editText_code);

        autologin();

        initImageLoader(LoginActivity.this);

        headDisplayOption=new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.djsx) // resource or drawable
                .showImageForEmptyUri(R.mipmap.djsx) // resource or drawable
                .showImageOnFail(R.mipmap.djsx)  // resource or drawable
//                .cacheInMemory(true) // default
//                .cacheOnDisk(true) // default
                .considerExifParams(false) // default
//                .displayer(new RoundedBitmapDisplayer(200))
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
                .bitmapConfig(Bitmap.Config.RGB_565) // default
                .build();

        findViewById(R.id.button_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                name=editText_username.getText().toString();
                passwd=editText_passwd.getText().toString();
                code=editText_code.getText().toString();

//                Intent ent = new Intent(LoginActivity.this,MainActivity.class);
//                startActivity(ent);

                if (name.length() == 0) {
                    ToastUtil.showToast(LoginActivity.this, "请输入用户名");
                } else if (passwd.length() == 0) {
                    ToastUtil.showToast(LoginActivity.this, "请输入密码");
                } else if (code.length() == 0) {
                    ToastUtil.showToast(LoginActivity.this, "请输入验证码");
                } else {
                    if (!CheckNetwork.hasNet(LoginActivity.this)) {
                        ToastUtil.showToast(LoginActivity.this, "无网络连接");
                    } else {
                        login();
                    }
                }
            }
        });

        findViewById(R.id.codeimg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCode();
            }
        });
        getCode();
    }

    private void autologin(){

        String namee = Sharedpreference.getAccount();
        String passwde = Sharedpreference.getPas();

        editText_username.setText(namee);
        editText_passwd.setText(passwde);
    }

    private void login(){
        LikoushanApi.login(LoginActivity.this,code,name,passwd, new ResponseInterface() {
            @Override
            public void onSuccess(Object obj) {
                Loginbean bean = (Loginbean) obj;
                if(bean.getResult_code().equals("1")){

                    Sharedpreference.setAccount(name);
                    Sharedpreference.setPas(passwd);
                    Sharedpreference.setSign(bean.getSign());
                    Sharedpreference.setUserid(bean.getUserid());
                    String type ="0";
                    Log.d("xing","aaaaaaaaaaa"+bean.getType()+"   "+bean.getType().contains("管理员"));
                    if (bean.getType().contains("管理员")){
                        type = "1";
                    }else{
                        type = "0";
                    }
                    Sharedpreference.setType(type);
                    Intent ent = new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(ent);
                }
            }

            @Override
            public void onFailed(String obj) {
                if(obj.equals("验证码错误")){
                    getCode();
                }
                ToastUtil.showToast(LoginActivity.this, obj);

            }
            @Override
            public void onMessage(String msg) {
                ToastUtil.showToast(LoginActivity.this, msg);
            }
        });
    }

    private void getCode(){

        LikoushanApi.getCode(LoginActivity.this, new ResponseInterface() {
            @Override
            public void onSuccess(Object obj) {
                Codebean beanl = (Codebean) obj;
                ImageLoader.getInstance().displayImage(beanl.getUrl(), codeimg, headDisplayOption);

            }

            @Override
            public void onFailed(String obj) {
                ToastUtil.showToast(LoginActivity.this, obj);
            }

            @Override
            public void onMessage(String msg) {
                ToastUtil.showToast(LoginActivity.this, msg);
            }
        });

    }

    public void initImageLoader(Context context) {

        mLocalStorageUtil = new LocalStorageUtil();
        mLocalStorageUtil.initLocalDir(LoginActivity.this);

        File cacheDir = new File(mLocalStorageUtil.getImageCacheAbsoluteDir());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCache(new UnlimitedDiscCache(cacheDir))
//				.writeDebugLogs() // Remove for release app
                .build();
        ImageLoader.getInstance().init(config);
    }

}
